package scaladuct.python;

/**
 * <p/>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Jan 19, 2011
 * Time: 8:24:45 PM
 */

import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Jython Object Factory using PySystemState
 */
public class JythonObjectFactory {

    private static JythonObjectFactory instance = null;

    protected JythonObjectFactory() {
    }

    /**
     * Create a singleton object. Only allow one instance to be created
     */
    public static JythonObjectFactory getInstance() {
        if (instance == null) {
            instance = new JythonObjectFactory();
        }

        return instance;
    }

    /**
     * The createObject() method is responsible for the actual creation of the
     * Jython object into Java bytecode.
     */
    public <T> T createObject(Class<T> interfaceType, String moduleName, String className) {
        Object javaInt = null;
        // Create a PythonInterpreter object and import our Jython module
        // to obtain a reference.
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("from " + moduleName + " import " + className);

        PyObject pyObject = interpreter.get(className);

        // Create a new object reference of the Jython module and
        // store into PyObject.
        PyObject newObj = pyObject.__call__();
        // Call __tojava__ method on the new object along with the interface name
        // to create the java bytecode
        javaInt = newObj.__tojava__(interfaceType);

        return (T)javaInt;
    }
}